package solutions;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2023-12-09
 * Time: 18:50
 */
//较难题！
// 现有一链表的头指针 ListNode* pHead，给一定值x，编写一段代码将所有小于x的结点排在其余结点之前，且不能改变原来的数据顺序，返回重新排列后的链表的头指针
public class Solution7 {
    public ListNode partition(ListNode pHead, int x) {
        // write code here
        if(pHead == null) {
            return null;
        }

        ListNode cur = pHead;
        //写出两个链表ab，并分别设置头尾结点as,ae,bs,be;
        ListNode as = null;
        ListNode ae = null;
        ListNode bs = null;
        ListNode be = null;
        while(cur != null) {
            //小于x的数据放在链表a:
            if(cur.val < x) {
                if(as == null) {
                    as = cur;
                    ae = cur;
                }else {
                    ae.next = cur;
                    ae = ae.next;
                }
            }else {
                if(bs == null) {
                    bs = cur;
                    be = cur;
                }else {
                    be.next = cur;
                    be = be.next;
                }
            }
            cur = cur.next;
        }
        if(bs != null) {
            be.next = null;
        }
        //修正可能会有一个链表为空的情况:
        if(as == null) {
            return bs;
        }
        //把两个链表拼接起来
        ae.next = bs;
        return as;

    }
}
